package com.lwq.controller;

import com.lwq.annotation.Log;
import com.lwq.dao.TaskMapper;
import com.lwq.service.TaskService;
import com.lwq.util.CronUtils;
import com.lwq.exception.FieldException;
import com.lwq.exception.TaskException;
import com.lwq.model.Dto;
import com.lwq.model.Dtos;
import com.lwq.model.Result;
import com.lwq.model.SysTask;
import com.lwq.util.TableDataInfo;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/16
 */
@RestController
public class TaskController extends BaseController {

    @Autowired
    private TaskService service;
    @Autowired
    private TaskMapper mapper;


    @GetMapping("/task")
    public TableDataInfo list(){
        Dto dto = Dtos.newDto(request);
        startPage();
        return getDataTable(service.queryList(dto));
    }

    @PostMapping("/task")
    @Log
    public Result add(@RequestBody @Valid SysTask model) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(model.getCron())){
            return Result.error("cron表达式不正确");
        }
        service.addTask(model);
        return Result.ok("新增定时任务成功");
    }

    @PutMapping("/task/changeStatus")
    @Log
    public Result changeStatus(@RequestBody @Valid SysTask model) throws SchedulerException {
        if(model.getId() == null){
            throw new FieldException("id不能为空");
        }
        SysTask task = mapper.selectById(model.getId());
        task.setStatus(model.getStatus());
        service.changeStatus(task);
        return Result.ok();
    }

    @PutMapping("/task/run")
    @Log
    public Result run(@RequestBody @Valid SysTask model) throws SchedulerException {
        service.run(model);
        return Result.ok("立即执行成功");
    }

    @DeleteMapping("/task/{id}")
    @Log
    public Result del(@PathVariable Long id) throws SchedulerException {
        service.deleteTask(id);
        return Result.ok("删除定时任务成功");
    }

}
